package com.yxt.service;

import java.util.ArrayList;
import java.util.List;

import com.yxt.dao.DBOperator;
import com.yxt.model.Division;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DivisionService {
	private DBOperator dbHelper;

	public DivisionService(Context context) {
		dbHelper = new DBOperator(context);
	}

	public List<Division> getDivisionByConditions(String condition) {
		List<Division> list = new ArrayList<Division>();
		SQLiteDatabase db = dbHelper.getDataBase();
		StringBuffer sql = new StringBuffer();
		sql.append("select code,name,type,parentcode from subdivisions");
		if (!"".equals(condition)) {
			sql.append(" where ");
			sql.append(condition);
		}
		Cursor cs = db.rawQuery(sql.toString(),null);
		
		while (cs.moveToNext()) {
			int index = 0;
			Division division = new Division();
			division.setCode(cs.getString(index++));
			division.setName(cs.getString(index++));
			division.setType(cs.getString(index++));
			division.setParentCode(cs.getString(index++));
			list.add(division);
		}
		cs.close();
		return list;
	}

	
	public Division getDivisionByCode(String code) {
		Division division = new Division();
		SQLiteDatabase db = dbHelper.getDataBase();
		Cursor cs = db.rawQuery("select code,name,type,parentcode from subdivisions where code = ?",new String[]{code});
		while (cs.moveToNext()) {
			int index = 0;
			division.setCode(cs.getString(index++));
			division.setName(cs.getString(index++));
			division.setType(cs.getString(index++));
			division.setParentCode(cs.getString(index++));
		}
		cs.close();
		return division;
	}
	
	public void closeDB() {
		dbHelper.close();
	}

}
